IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'spPressreleasesInsertIfNotExist') AND type in (N'P', N'PC'))
	DROP PROCEDURE spPressreleasesInsertIfNotExist
GO
-- =============================================
-- [20-Aug-2014 Nam Tran]
-- Insert new pressrelease if it's not existing in DB
-- =============================================
CREATE PROCEDURE spPressreleasesInsertIfNotExist
	@DateTime DATETIME,
	@DateNumberic BIGINT,
	@SourceCode VARCHAR(150),
	@LangId INT,
	@Message NVARCHAR(MAX),	
	@Title NVARCHAR(500),
	@Attachment BIT,
	@SourceId INT,	
	@MessageTypeId INT
AS
BEGIN

DECLARE @PressreleasesId BIGINT = NULL

	-- Try to find existing pressrelease which has same Title and Date
	SET @PressreleasesId = (SELECT TOP 1 Id FROM Pressreleases 
							WHERE Title = @Title 
								AND DateNumeric = @DateNumberic 
								AND SourceID = @SourceId 
								AND SourceCode = @SourceCode
								AND LangId = @LangId)

	IF(@PressreleasesId IS NULL)
	BEGIN
		INSERT INTO Pressreleases(  
			  [DateTime]
			  ,[DateNumeric]
			  ,[SourceCode]
			  ,[LangId]
			  ,[Message]
			  ,[Title]			  		  
			  ,[Attachment]
			  ,[SourceId]
			  ,[CreatedOn]
			  ,[DisplayOrder]
			  ,[Published]
			  ,[MessageTypeId])
			VALUES(
			   @DateTime
			  ,@DateNumberic
			  ,@SourceCode
			  ,@LangId
			  ,@Message
			  ,@Title
			  ,@Attachment
			  ,@SourceId
			  ,GETDATE()
			  ,0
			  ,1
			  ,@MessageTypeId
			)
			SET @PressreleasesId = SCOPE_IDENTITY()
	END
	IF @PressreleasesId IS NULL
		SET @PressreleasesId = -1
	SELECT @PressreleasesId
END

